<script setup>
import axiosInstance from '@/utils/request'
import { defineProps, reactive } from 'vue'
import { showFailToast } from 'vant'

const props = defineProps({
  isShow: Boolean
})
const emits = defineEmits(['onClickCloseIcon'])
const onClickCloseIcon = () => {
  emits('onClickCloseIcon', false)
}
const data = reactive({
  isShow: props.isShow,
  username: '',
  password: '',
  nickname: ''
})
const reset = () => {
  data.username = ''
  data.nickname = ''
  data.password = ''
}
const onRegister = () => {
  // 非空校验
  if (!data.username || !data.password || !data.nickname) {
    showFailToast('字段不能为空')
    return
  }
  axiosInstance
    .post('/user/register', {
      nickname: data.nickname,
      username: data.username,
      password: data.password
    })
    .then((response) => {
      if (response.data.code === 40001) {
        showFailToast(response.data.msg)
        return
      }
      showSuccessToast(response.data.msg)
      emits('onClickCloseIcon', false)
      reset()
    })
    .catch((error) => {
      showFailToast('注册失败')
    })
}
</script>
<template>
  <van-popup
    style="padding: 10px"
    v-model:show="data.isShow"
    closeable
    position="bottom"
    :style="{ height: '40%' }"
    @click-close-icon="onClickCloseIcon"
  >
    <h2>注册</h2>
    <van-form @submit="onRegister">
      <van-cell-group inset>
        <van-field
          v-model="data.nickname"
          required
          name="昵称"
          label="昵称"
          placeholder="昵称"
        />
        <van-field
          v-model="data.username"
          required
          name="账号"
          label="账号"
          placeholder="账号"
        />
        <van-field
          v-model="data.password"
          required
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
        />
      </van-cell-group>
      <div style="margin: 16px" @click="onRegister">
        <van-button round block type="primary" color="#0c34ba">
          注册
        </van-button>
      </div>
    </van-form>
  </van-popup>
</template>
<style scoped></style>
